// 环形链表
#ifndef _LUV_LIST_H
#define _LUV_LIST_H
#include <stddef.h>

typedef void* list_node_t[2];

// 私有接口
#define _list_pre(n) (*(list_node_t**)&((*(n))[0]))
#define _list_next(n) (*(list_node_t**)&((*(n))[1]))

#define list_head_init(name) list_node_t name = {&(name), &(name)}
#define list_empty(h) (h) == _list_next(h)
#define list_data(ptr, type, field) \
    ((type*)((char*)(ptr)-offsetof(type, field)))
#define list_foreach(n, h) for (n = _list_next(h); n != (h); n = _list_next(n))
#define list_foreach_safe(n, nn, h)                       \
    for (n = _list_next(h), nn = _list_next(n); n != (h); \
         n = nn, nn = _list_next(n))

// 在两个节点直接插入新的元素
extern inline void list_insert(list_node_t* pre, list_node_t* next,
                               list_node_t* new_node) {
    _list_pre(new_node) = pre;
    _list_next(new_node) = next;
    _list_next(pre) = new_node;
    _list_pre(next) = new_node;
}

// 在链表尾部添加元素
extern inline void list_append(list_node_t* head, list_node_t* new_node) {
    list_insert(_list_pre(head), head, new_node);
}

#endif  //_LUV_LIST_H